// CSE 142, Winter 2008, Marty Stepp // // This program draws random 10x10 rectangles on a DrawingPanel with random // positions and colors until it has drawn 20 total red rectangles. // The program demonstrates random numbers, while loops, and graphics. import java.awt.*; // for Graphics, Point import java.util.*; // for Random public class RandomRectangles2 { // set to false to turn off println messages public static final boolean DEBUG = true; public static void main(String[] args) { DrawingPanel panel = new DrawingPanel(500, 500); Graphics g = panel.getGraphics(); Random rand = new Random(); // keep drawing rectangles until we get 20 red ones Point p = new Point(); int reds = 0; while (reds < 20) { if (drawRandomRect(g, rand, p)) { // then we drew a red rectangle reds++; if (DEBUG) { System.out.println("Drew red rect #" + reds + " at " + p.x + "," + p.y); } } } } // Returns true if we drew a red rectangle, false otherwise. public static boolean drawRandomRect(Graphics g, Random rand, Point p) { // choose a random location p.x = rand.nextInt(490) + 1; p.y = rand.nextInt(490) + 1; // choose a random color int randomColor = rand.nextInt(3); // 0 -- 2 if (randomColor == 0) { g.setColor(Color.RED); } else if (randomColor == 1) { g.setColor(Color.GREEN); } else { // 2 g.setColor(Color.BLUE); } g.fillRect(p.x, p.y, 10, 10); // return whether or not we drew a red rectangle if (randomColor == 0) { return true; } else { return false; } } }